import sys
import re
import os
import time
import clipboard

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

WRITE_FILE = 1
TO_CLIPBOARD = 2

VIEWBASE = 1  #
COMMEX = 2  #
DATATEMPLATE = 3  #
COMMON = 4  #
SIGNAL = 5  #
NET_SIGNAL = 6  #

filepath = ""
filename = "None"
retype = 1
flag = 1
print(sys.argv.count)
if len(sys.argv) > 1:
    filepath = sys.argv[1]
if len(sys.argv) > 2:
    filename = sys.argv[2]
if len(sys.argv) > 3:
    retype = int(sys.argv[3])
if len(sys.argv) > 4:
    flag = int(sys.argv[4])

dic = {}

dic[VIEWBASE] = """--- author:liushiyin
--- date: #time#
--- des: #des#
local ViewBase = require("app.ui.ViewBase")
local #name# = class("#name#", ViewBase)

function #name#:ctor()
	local resource = {
		file = Path.getCSB("#name#", "#view_path#"),
		size = G_ResolutionManager:getDesignSize(),
		binding = {
		    #bind_event#
		}
	}
	# name#.super.ctor(self, resource)
end

function #name#:onCreate()
end

function #name#:onEnter()
end

function #name#:onExit()
end

#content_func#

return #name#
"""

dic[COMMEX] = """--- author:liushiyin
--- date: #time#
--- des: #des#
local CommonBaseEx = require("app.ui.CommonBaseEx")
local #name# = class("#name#", CommonBaseEx)

function #name#:ctor(target)
    local binding = {
        #bind_event#
    }
    # name#.super.ctor(self, target, binding)
end

function #name#:onCreate()
end

#content_func#

return #name#
"""

dic[DATATEMPLATE] = """--- author:liushiyin
--- date: #time#
--- des: #des#
local BaseData = require("app.data.BaseData")
local #name# = class("#name#", BaseData)

local schema = {}
# name#.schema = schema

function #name#:ctor(properties)

end

function #name#:clear()
end

function #name#:reset()

end

return #name#
"""

dic[COMMON] = """--- author:liushiyin
--- date: #time#
--- des: #des#
local #name# = class("#name#")

# name#.EXPORTED_METHODS = {

}

function #name#:ctor()

end

function #name#:_init()

end

function #name#:bind(target)
	self._target = target
    self:_init()
    cc.setmethods(target, self, self.class.EXPORTED_METHODS)
end

function #name#:unbind(target)
    cc.unsetmethods(target, self.class.EXPORTED_METHODS)
end

return #name#
"""

dic[SIGNAL] = """
function #name#:onEnter()
	G_SignalManager:beginCache(self.__cname)
    #signal_event#
	G_SignalManager:endCache()
end

function #name#:onExit()
	G_SignalManager:removeCache(self.__cname)
end


"""

dic[NET_SIGNAL] = """--- author:liushiyin
--- date: #time#
--- des: #des#
local BaseData = require("app.data.BaseData")
local #name# = class("#name#", BaseData)

local schema = {}
# name#.schema = schema

function #name#:ctor(properties)
	G_NetworkManager:beginCache(self.__cname)
    #net_signal_event#
	G_NetworkManager:endCache()
end

function #name#:clear()
	G_NetworkManager:removeCache(self.__cname)
end

function #name#:reset()

end

"""

repl = ""
returnString = ""

repl = dic[retype]
returnString = repl.replace("#name#", filename)
returnString = returnString.replace("# name#", filename)
returnString = returnString.replace(
    "#time#", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

list = filepath.split(".")
length = len(list)
dirname = list[length - 1]
returnString = returnString.replace("#view_path#", dirname)

NODE_TYPE = "AbstractNodeData"
BUTTON_TYPE = "ButtonObjectData"
PROJECT_NODE = "ProjectNodeObjectData"


def mkdir(path):
    folder = os.path.exists(path)
    if not folder:
        os.makedirs(path)
    else:
        print("---  There is this folder!  ---")


class XMLParser:
    def __init__(self):
        self.bind_event_string = ""
        self.bind_event_func = ""

    def paserCsd(self, filepath, filename):
        self.filepath = filepath
        self.filename = filename

        list = filepath.split(".")
        length = len(list)
        dirname = list[length - 1]
        curpath = os.getcwd()
        csdPath = curpath + "\\..\\csui\\" + dirname + "\\" + filename + ".csd"
        # mkdir(curpath + "\\..\\csui\\" + dirname + "\\")
        # csdfileOb = open(csdPath, "w+")
        # csdfileOb.close()
        xmlRoot = ET.ElementTree(file=csdPath)
        # xmlRoot.getroot()
        # print (xmlRoot)
        # print (xmlRoot.getroot().ta)
        self.xmlTree(xmlRoot.getroot())
        # filecsd=open(csdPath)

    def xmlTree(self, root):
        for child in root:
            if child.tag == NODE_TYPE:
                # print child.tag, child.attrib
                if child.attrib.has_key('ctype'):
                    if child.attrib['ctype'] == BUTTON_TYPE:
                        childName = child.attrib['Name']
                        ret = childName.find("_")
                        if ret == 0:
                            tempName = childName.replace("_", "")
                            tempName = tempName[0].upper() + tempName[1:]
                            self.bind_event_string = self.bind_event_string + childName + \
                                " = {events = {{event = \"touch\", method = \"_on" + \
                                tempName + "Clicked\"}}},\n"
                            func_one = "function #name#:#func_name#()\n\nend\n"
                            func_one = func_one.replace("#name#", filename)
                            func_one = func_one.replace(
                                "#func_name#", "_on" + tempName + "Clicked")
                            self.bind_event_func = self.bind_event_func + func_one + "\n"
            self.xmlTree(child)

    def getBindString(self):
        return self.bind_event_string

    def getBindFunc(self):
        return self.bind_event_func


def SignalProcess(inStr, signalList, filename):
    signal_string = ""
    signal_func = ""
    returnString = inStr
    for event_name in signalList:
        func_name = "_on"
        temps = event_name.split("_")
        for temp in temps:
            temp = temp.lower()
            temp = temp[0].upper() + temp[1:]
            func_name = func_name + temp
        signal_string_one = """ G_SignalManager:add(SignalConst.#event_name#, handler(self, self.#func_name#)) \n    """
        signal_string_one = signal_string_one.replace(
            "#event_name#", event_name)
        signal_string_one = signal_string_one.replace("#func_name#", func_name)
        signal_func_one = """function  #name#:#func_name#(id,...)\n\nend\n\n"""
        signal_func_one = signal_func_one.replace("#name#", filename)
        signal_func_one = signal_func_one.replace("#func_name#", func_name)
        signal_string = signal_string + signal_string_one
        signal_func = signal_func + signal_func_one
    returnString = returnString.replace("#signal_event#", signal_string)
    returnString = returnString + signal_func
    return returnString


def getCsProtoS2C(ID):
    ID = ID.replace("ID_", "")
    ID = ID.strip()
    ID = ID.rstrip()
    curpath = os.getcwd()
    cspath = curpath + "\\..\\res\\proto\\cs.proto"
    filecs = open(cspath, "r")
    line = filecs.readline()
    start = 0
    csBuff = []
    while line:
        if start == 1:
            temp = line.strip()
            temp = temp.rstrip()
            csBuff.insert(0, temp)
        ret = line.find(ID)
        ret2 = line.find("{")
        ret3 = line.find("}")
        if ret != -1 and ret2 != -1:
            start = 1
        elif ret3 != -1:
            start = 0
        line = filecs.readline()
    return csBuff


def getCsProtoC2S(ID):
    ID = ID.replace("ID_", "")
    ID = ID.strip()
    ID = ID.rstrip()
    ID = ID.replace("S", "C", 1)
    ID = ID[0] + ID[1:].replace("C", "S", 1)
    curpath = os.getcwd()
    cspath = curpath + "\\..\\res\\proto\\cs.proto"
    filecs = open(cspath, "r")
    line = filecs.readline()
    start = 0
    csBuff = []
    # print (ID)
    while line:
        if start == 1:
            temp = line.strip()
            temp = temp.rstrip()
            csBuff.insert(0, temp)
        ret = line.find(ID)
        ret2 = line.find("{")
        ret3 = line.find("}")
        if ret != -1 and ret2 != -1:
            start = 1
        elif ret3 != -1:
            start = 0
        line = filecs.readline()
    return csBuff


def getS2CParams(ID):
    csBuff = getCsProtoS2C(ID)
    rawgetStr = ""
    for one in csBuff:
        list = one.split(" ")
        if len(list) >= 3:
            if list[2] != "ret":
                rawgetStr = rawgetStr + "local " + \
                    list[2] + " = rawget(message,\"" + list[2] + "\") \n"
            # print (list)
    # print (rawgetStr)
    return rawgetStr


def getC2SParams(ID):
    csBuff = getCsProtoC2S(ID)
    params = ""
    setParams = ""
    # print (csBuff)
    for one in range(len(csBuff)):
        list = csBuff[one].split(" ")
        if len(list) >= 3:
            # print (one)
            if one < len(csBuff) - 1:
                params = params + list[2] + " , "
                setParams = setParams + list[2] + " = " + list[2] + " , \n"
            else:
                params = params + list[2]
                setParams = setParams + list[2] + " = " + list[2]

    retDic = {}
    retDic[1] = params
    retDic[2] = setParams
    print(retDic)
    return retDic


def NetSignalProcess(inStr, signalList, filename):
    signal_string = ""
    signal_func = ""
    signal_send_func = ""
    returnString = inStr
    for event_name in signalList:
        func_name = "_"
        func_send_name = ""
        event_name = event_name.replace("ID_", "")
        temps = event_name.split("_")
        count = 0
        for temp in temps:
            temp = temp.lower()
            if count > 0:
                temp = temp[0].upper() + temp[1:]
            func_name = func_name + temp
            temp = temp.replace("s", "c")
            temp = temp[0] + temp[1:].replace("c", "s")
            func_send_name = func_send_name + temp
            count = count + 1
        signal_string_one = """ G_NetworkManager:add(MessageIDConst.ID_#event_name#, handler(self, self.#func_name#)) \n    """
        signal_string_one = signal_string_one.replace(
            "#event_name#", event_name)
        signal_string_one = signal_string_one.replace("#func_name#", func_name)
        signal_func_one = """function  #name#:#func_name#(id,message)\n if message.ret~=1 then\n    return \n   end\n #rawget# end\n\n"""
        signal_func_one = signal_func_one.replace("#name#", filename)
        signal_func_one = signal_func_one.replace("#func_name#", func_name)
        retGet = getS2CParams(event_name)
        signal_func_one = signal_func_one.replace("#rawget#", retGet)
        signal_func_send_one = """function  #name#:#func_name#(#param#)\n 	G_NetworkManager:send(MessageIDConst.ID_#event_name#,{#setParam#}) \nend\n\n"""
        signal_func_send_one = signal_func_send_one.replace("#name#", filename)
        signal_func_send_one = signal_func_send_one.replace(
            "#func_name#", func_send_name)
        temp_event_name = event_name.replace("S", "C")
        temp_event_name = temp_event_name[0] + \
            temp_event_name[1:].replace("C", "S", 1)
        signal_func_send_one = signal_func_send_one.replace(
            "#event_name#", temp_event_name)
        retDic = getC2SParams(event_name)
        signal_func_send_one = signal_func_send_one.replace(
            "#param#", retDic[1])
        signal_func_send_one = signal_func_send_one.replace(
            "#setParam#", retDic[2])
        signal_string = signal_string + signal_string_one
        signal_func = signal_func + signal_func_one
        signal_send_func = signal_send_func + signal_func_send_one

    returnString = returnString.replace("#net_signal_event#", signal_string)
    returnString = returnString + signal_send_func
    returnString = returnString + signal_func
    returnString = returnString + "\nreturn " + filename
    return returnString


if retype == VIEWBASE:
    try:
        xmlPa = XMLParser()
        xmlPa.paserCsd(filepath, filename)
        returnString = returnString.replace(
            "#bind_event#", xmlPa.getBindString())
        returnString = returnString.replace(
            "#content_func#", xmlPa.getBindFunc())
    except ImportError:
        returnString = returnString.replace("#bind_event#", "")
        returnString = returnString.replace("#content_func#", "")
elif retype == SIGNAL:
    fileSignal = open("signal.txt", "r")
    lines = fileSignal.readlines()
    returnString = SignalProcess(returnString, lines, filename)
elif retype == NET_SIGNAL:
    fileSignal = open("signal.txt", "r")
    lines = fileSignal.readlines()
    returnString = NetSignalProcess(returnString, lines, filename)
else:
    pass

if flag == WRITE_FILE:
    print("write to file")
    curpath = os.getcwd()
    filepath = filepath.replace(".", "\\")
    filepath = "\\" + filepath
    if filepath != "\\":
        filepath = filepath + "\\"
    fullpath = curpath + filepath
    mkdir(fullpath)
    fileObject = open(fullpath + filename + ".lua", "w+")
    fileObject.write(returnString)
    fileObject.close()
elif flag == TO_CLIPBOARD:
    print("to clipboard")
    clipboard.copy(returnString)  # content put to clipboard

# print (bing_event_string)
# print(returnString)
